package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC735 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int[] asteroidCollision(int[] asteroids) {
            Stack<Integer> stack = new Stack<>();
            for (int asteroid : asteroids) {
                if (stack.isEmpty() || stack.peek() * asteroid > 0 || (stack.peek() < 0 && asteroid > 0)) {
                    stack.push(asteroid);
                    continue;
                }

                //两个数字：peek为正，asteroid为负
                boolean insertCur = true;
                while (!(stack.isEmpty() || stack.peek() * asteroid > 0 || (stack.peek() < 0 && asteroid > 0))) {
                    if (stack.peek() < Math.abs(asteroid)) stack.pop();
                    else if (stack.peek() == Math.abs(asteroid)) {
                        stack.pop();
                        insertCur = false;
                        break;
                    } else {
                        insertCur = false;
                        break;
                    }
                }
                if (insertCur) stack.push(asteroid);
            }

            int[] res = new int[stack.size()];
            for (int i = res.length - 1; i >= 0; i--) {
                res[i] = stack.pop();
            }
            return res;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[-2,-1,1,2]");
        System.out.println(Arrays.toString(solution.asteroidCollision(arr)));
    }

    public static void main(String[] args) throws Exception {
        LC735 an = new LC735();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
